package com.example.kotlineventtracker.view

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlineventtracker.R
import com.example.kotlineventtracker.databinding.ItemEventInfoBinding
import com.example.kotlineventtracker.databinding.ItemEventInfoHeaderBinding
import com.example.kotlineventtracker.model.EventInfo

class EventInfoAdapter(private var eventInfoList: List<EventInfo>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // 头部 ViewHolder
    class HeaderViewHolder(private val binding: ItemEventInfoHeaderBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(headerTitle: String, headerPv: String, headerUv: String) {
            binding.date.text = headerTitle
            binding.pv.text = headerPv
            binding.uv.text = headerUv
        }
    }

    // 事件信息 ViewHolder
    class EventInfoViewHolder(private val binding: ItemEventInfoBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(eventInfo: EventInfo) {
            binding.date.text = eventInfo.eventDate
            binding.pv.text = eventInfo.pv.toString()
            binding.uv.text = eventInfo.uv.toString()
        }
    }

    companion object {
        const val TYPE_HEADER = 0
        const val TYPE_ITEM = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_HEADER -> {
                val binding = ItemEventInfoHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                HeaderViewHolder(binding)
            }
            TYPE_ITEM -> {
                val binding = ItemEventInfoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                EventInfoViewHolder(binding)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder.itemViewType) {
            TYPE_HEADER -> {
                // 绑定头部数据
                (holder as HeaderViewHolder).bind("日期", "PV", "UV")
            }
            TYPE_ITEM -> {
                // 绑定事件信息数据
                (holder as EventInfoViewHolder).bind(eventInfoList[position - 1])
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) TYPE_HEADER else TYPE_ITEM
    }

    override fun getItemCount(): Int {
        // 由于添加了头部，所以总项数是事件信息的数量加1
        return eventInfoList.size + 1
    }
}